package com.lap.context.starter.helper;

import com.lap.context.starter.interceptor.UserContextInterceptor;
import com.lap.context.starter.entity.ContextDefinition;

import java.util.Objects;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;

/**
 * 提供微服务获取当前请求的用户信息
 *
 * @author Shuisheng.Lao
 * @version 0.0.1
 * @see UserContextInterceptor
 */
@Slf4j
public final class UserHelper {

  private static final String SYSTEM_USER = "System";
  private static final ThreadLocal<ContextDefinition> THREAD_LOCAL = new ThreadLocal<>();

  private UserHelper() {
    throw new UnsupportedOperationException("Utility class cannot be instantiated");
  }

  public static void set(ContextDefinition context) {
    if (Objects.isNull(THREAD_LOCAL.get())) THREAD_LOCAL.set(context);
  }

  public static ContextDefinition get() {
    return THREAD_LOCAL.get();
  }

  public static void remove() {
    THREAD_LOCAL.remove();
  }

  public static Integer getUserId() {
    return getContextValue(ContextDefinition::getUserId, -1);
  }

  public static String getUsername() {
    return getContextValue(ContextDefinition::getUsername, SYSTEM_USER);
  }

  public static String getFullName() {
    return getContextValue(ContextDefinition::getFullName, SYSTEM_USER);
  }

  private static <T> T getContextValue(Function<ContextDefinition, T> extractor, T defaultValue) {
    ContextDefinition context = get();
    if (context != null) {
      return extractor.apply(context);
    }
    log.warn("获取用户失败，使用默认系统(System)");
    return defaultValue;
  }
}
